import Redis from 'ioredis'

const host = process.env.REDIS_HOST
const port = process.env.REDIS_PORT ? Number(process.env.REDIS_PORT) : undefined
const password = process.env.REDIS_PASSWORD

// Do NOT hardcode credentials in repository. Require env vars.
let client: any

if (!host || !port || !password) {
  // eslint-disable-next-line no-console
  console.warn('[redis] REDIS_HOST, REDIS_PORT or REDIS_PASSWORD not set. Redis is disabled.\nPlease set REDIS_HOST, REDIS_PORT and REDIS_PASSWORD in environment to enable Redis.')

  // Provide a dummy client with same methods used in the project so callers get consistent errors
  client = {
    get: async () => {
      throw new Error('Redis not configured: set REDIS_HOST, REDIS_PORT, REDIS_PASSWORD')
    },
    incr: async () => {
      throw new Error('Redis not configured: set REDIS_HOST, REDIS_PORT, REDIS_PASSWORD')
    }
  }
} else {
  // Create a single shared Redis client for server runtime
  const redis = new Redis({
    host,
    port,
    password,
    // lazyConnect avoids connecting until first command in some environments
    lazyConnect: false,
    // optional: enable auto pipelining for throughput
    enableAutoPipelining: true
  })

  redis.on('error', (err) => {
    // eslint-disable-next-line no-console
    console.error('[redis] error', err)
  })

  client = redis
}

export default client
